const { Service } = require('ee-core');
const SerialPort = require('serialport');


class SerialPortService extends Service {
  private port: SerialPort;
  private events: []
  constructor(ctx) {
    super(ctx);
    this.port = new SerialPort('/dev/ttyS0', { baudRate: 38400 }); // Replace 'COM3' with your port

    this.port.on('open', () => {
      this.ctx.logger.info('Serial Port Opened');
    });

    this.port.on('data', (data) => {
      this.ctx.logger.info('Data received:', data.toString());
      this.events.forEach(event => event(data))
    });

    this.port.on('error', (err) => {
      this.ctx.logger.error('Serial Port Error:', err.message);
    });
  }


  onMessage(callback) {
    events.push(callback)
  }
  off(callback) {
    events = events.filter((fn) => {
      const flag = fn.toString() !== callback.toString() &&  String(fn.callback) !== callback.toString();
      return flag;
    })

  }

  // Add methods to interact with the serial port
  async sendData(data: string) {
    return new Promise<void>((resolve, reject) => {
      this.port.write(data, (err) => {
        if (err) {
          reject(err);
        } else {
          resolve();
        }
      });
    });
  }
}

SerialPortService.toString = () => '[class SerialPortService]';
module.exports = SerialPortService;  